Page({
  data: {
    userId: null,
    groupedWorks: {},
    groupedWorksArray: [],
    currentPage: 1,
    pageSize: 10,
    hasMore: true,
    isLoading: false,
  },

  onLoad() {
    const userDetails = wx.getStorageSync('userDetails');
    if (userDetails && userDetails.id) {
      this.setData({ userId: userDetails.id });
      this.loadWorks();
    } else {
      wx.showToast({
        title: '用户信息获取失败',
        icon: 'none',
      });
    }
  },

  loadWorks() {
    const { userId, currentPage, pageSize } = this.data;
    this.setData({ isLoading: true });

    wx.request({
      url: 'http://localhost:8080/user/work/page',
      method: 'GET',
      data: {
        userId: userId,
        page: currentPage,
        pageSize: pageSize,
      },
      success: (res) => {
        if (res.data.code == 1) {
          const works = res.data.data.records;
          const total = res.data.data.total;
          this.groupWorksByYearAndMonth(works);
          const hasMore = currentPage * pageSize < total;
          this.setData({ hasMore });
        } else {
          wx.showToast({
            title: '数据加载失败',
            icon: 'none',
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '请求失败',
          icon: 'none',
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      },
    });
  },

  groupWorksByYearAndMonth(works) {
    const groupedWorks = { ...this.data.groupedWorks };

    works.forEach((work) => {
      if (work.userId === this.data.userId && work.updateTime && work.urlList) {
        const date = new Date(work.updateTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');

        if (!groupedWorks[year]) {
          groupedWorks[year] = {};
        }
        if (!groupedWorks[year][month]) {
          groupedWorks[year][month] = [];
        }

        const urlList = work.urlList.split(',').map(url => {
          if (!url.startsWith('http')) {
            return `https://${url}`;
          }
          return url;
        });
        groupedWorks[year][month].push(...urlList);
      }
    });

    const groupedWorksArray = Object.keys(groupedWorks).map(year => {
      return {
        year,
        months: Object.keys(groupedWorks[year]).map(month => {
          return {
            month,
            images: groupedWorks[year][month]
          };
        })
      };
    });

    this.setData({ groupedWorks, groupedWorksArray });
  },

  onImageError(e) {
    console.error('图片加载失败:', e.detail.errMsg);
  },

  loadMore() {
    if (this.data.hasMore) {
      const nextPage = this.data.currentPage + 1;
      this.setData({ currentPage: nextPage });
      this.loadWorks();
    }
  },

  onPullDownRefresh() {
    this.setData({
      groupedWorks: {},
      groupedWorksArray: [],
      currentPage: 1,
      hasMore: true,
    });
    this.loadWorks();
    wx.stopPullDownRefresh();
  },

  onReachBottom() {
    this.loadMore();
  },
});